import { useState, useEffect } from 'react';

export function useTheme() {
  const [darkMode, setDarkMode] = useState(false);

  useEffect(() => {
    // 初始化主题
    const savedTheme = localStorage.getItem('theme');
    const prefersColorScheme = window.matchMedia('(prefers-color-scheme: dark)');
    const systemPrefersDark = prefersColorScheme.matches;

    let isDark = false;
    if (savedTheme === 'light') {
      isDark = false;
    } else if (savedTheme === 'dark') {
      isDark = true;
    } else {
      isDark = systemPrefersDark;
      localStorage.setItem('theme', isDark ? 'dark' : 'light');
    }

    setDarkMode(isDark);
    updateDOMTheme(isDark);

    // 监听主题变化事件
    const handleThemeChange = (e: CustomEvent) => {
      const newTheme = e.detail.theme;
      const newDarkMode = newTheme === 'dark';
      setDarkMode(newDarkMode);
      updateDOMTheme(newDarkMode);
    };

    window.addEventListener('themeChange', handleThemeChange as EventListener);

    return () => {
      window.removeEventListener('themeChange', handleThemeChange as EventListener);
    };
  }, []);

  const updateDOMTheme = (isDark: boolean) => {
    if (isDark) {
      document.documentElement.classList.add('dark');
    } else {
      document.documentElement.classList.remove('dark');
    }
  };

  const toggleTheme = () => {
    const newDarkMode = !darkMode;
    const newTheme = newDarkMode ? 'dark' : 'light';
    
    setDarkMode(newDarkMode);
    updateDOMTheme(newDarkMode);
    localStorage.setItem('theme', newTheme);
    
    // 通知其他组件
    window.dispatchEvent(new CustomEvent('themeChange', {
      detail: { theme: newTheme }
    }));
  };

  return { darkMode, toggleTheme };
} 